import { Context, createContext, FC, ReactNode, useContext } from 'react';
import { stringify } from 'qs';
import { NavigateFunction, NavigateOptions, useNavigate } from 'react-router-dom';

export type FcNavigateValue = { [key: string]: string };

const FcNavigateContext: Context<FcNavigateValue> = createContext(null);

export interface NavigateProviderProps {
  value: FcNavigateValue;
  children?: ReactNode | undefined;
}

export const FcNavigateProvider: FC<NavigateProviderProps> = ({ value, children }) => {
  return <FcNavigateContext.Provider value={value}>{children}</FcNavigateContext.Provider>;
};

const useFcNavigate = () => {
  const context = useContext(FcNavigateContext);
  const navigate: NavigateFunction = useNavigate();

  return (
    key: string,
    options?: {
      originOptions?: NavigateOptions;
      searchParams?: { [key: string]: any };
      params?: { [key: string]: string | number };
    },
  ) => {
    if (context[key]) {
      const query: string = options?.searchParams ? `?${stringify(options?.searchParams, { encode: false })}` : '';

      let pathname: string = context[key];

      if (options?.params) {
        Object.keys(options?.params).forEach((key: string) => {
          pathname = pathname.replace(`:${key}`, options?.params[key].toString());
        });
      }

      navigate(pathname + query, options?.originOptions);
    } else {
      navigate(key, options?.originOptions);
    }
  };
};

export default useFcNavigate;
